<?php

namespace C\P;

class UCPaas
{
    private $appId;
    private $accountSid;
    private $authToken;

    /**
     * @param $appId
     * @param $accountSid
     * @param $authToken
     */
    public function __construct($appId, $accountSid, $authToken)
    {
        $this->appId = $appId;
        $this->accountSid = $accountSid;
        $this->authToken = $authToken;
    }

     /**
     * @param $mobile
     * @param $templateId
     * @param $params
     */
   
    public function send($mobile, $templateId, $params)
    {
        if (! $templateId) {
            throw new \Exception('template_id is not exists');
        }

        $url = 'https://open.ucpaas.com/ol/sms/sendsms';
        $requestParams = [
            'appid'      => $this->appId,
            'sid'        => $this->accountSid,
            'token'      => $this->authToken,
            'templateid' => $templateId,
            'param'      => implode(',', $params),
            'mobile'     => $mobile,
        ];

        $headers = [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json; charset=utf-8',
        ];

        $jsonResponse = Http::post($url, json_encode($requestParams), $headers, 10);
        if (! $jsonResponse) {
            throw new \Exception('请求异常');
        }

        $response = json_decode($jsonResponse, true);
        if ($response['code'] != '000000') {
            throw new \Exception($response['msg']);
        }

        return true;
    }
}
